﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;

namespace Inaction.Business.Security
{
    [Serializable]
    public class QueryTableDataCommand : Inaction.SqlCommand 
    {
        string table;
        List<string> columns;

        public DataTable Data { get;private set; }

        public QueryTableDataCommand(string table, List<string> columns)
        {
            this.table = table;
            if(columns.Count==0)
            {
                columns.Add("*");
            }
            this.columns = columns;
        }
        protected override void DoExecute(IDbConnection connection)
        {
            string sqlStr = "SELECT " + string.Join<string>(",", columns) + " FROM " + table;
            using (var command =connection.CreateCommand())
            {
                command.CommandText = sqlStr;
                Data = new DataTable();
                var reader = command.ExecuteReader();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    Data.Columns.Add(reader.GetName(i));
                }
                while (reader.Read())
                {
                    var row = Data.NewRow();
                    foreach (DataColumn colum in Data.Columns)
                    {
                        row[colum.ColumnName] = reader[colum.ColumnName];
                    }
                    Data.Rows.Add(row);
                }
            }
        }

      
    }
}
